<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="Username" prop="name">
        <el-input
          v-model="ruleForm.name"
          type="text"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="Password" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
import { ElForm } from 'element-plus'
import LocalCache from '@/utils/cache'
import { useStore } from 'vuex'
export default defineComponent({
  setup() {
    const store = useStore()
    const ruleForm = reactive({
      name: LocalCache.getCache('name') ?? '',
      password: LocalCache.getCache('password') ?? ''
    })

    const rules = reactive({
      name: [{ required: true, message: '用户名必传!', trigger: 'blur' }],
      password: [{ required: true, message: '密码必传!', trigger: 'blur' }]
    })

    const ruleFormRef = ref<InstanceType<typeof ElForm>>()

    const loginAction = (isKeepPassword: boolean) => {
      ruleFormRef.value?.validate((valid) => {
        if (valid) {
          //1.判断是否需要记住密码
          if (isKeepPassword) {
            LocalCache.setCache('name', ruleForm.name)
            LocalCache.setCache('password', ruleForm.password)
          } else {
            LocalCache.delete('name')
            LocalCache.delete('password')
          }
          //2.开始进行登录验证
          store.dispatch('loginModule/accountLoginAction', { ...ruleForm })
        }
      })
    }
    return {
      ruleForm,
      rules,
      loginAction,
      ruleFormRef
    }
  }
})
</script>

<style scoped></style>
